package jlxy.ise.eroad.fragment;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import cz.msebera.android.httpclient.Header;
import jlxy.ise.eroad.R;
import jlxy.ise.eroad.activity.LoginActivity;
import jlxy.ise.eroad.base.BaseSwitchFragment;
import jlxy.ise.eroad.bean.NlServerRps;
import jlxy.ise.eroad.bean.ServerRpsInfo;
import jlxy.ise.eroad.util.SingleToast;
import jlxy.ise.eroad.util.WebUtil;


/**
 * 注册界面
 *
 * @author chen
 */
public class LoginRegFragment extends BaseSwitchFragment implements
        OnClickListener {

    private Button mBtnReg;

    private EditText mEtUserNickName;
    private EditText mEtUserPhone;
    private EditText mEtUserPassword;
    private EditText mEtUserPasswordAgain;
    private TextView mTxBack;
    private ProgressDialog progressDialog;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_register, container,
                false);
        mBtnReg = (Button) rootView.findViewById(R.id.button_i_need_register);
        mEtUserNickName = (EditText) rootView
                .findViewById(R.id.editText_register_nickname);
        mEtUserPhone = (EditText) rootView
                .findViewById(R.id.editText_register_phone);
        mEtUserPassword = (EditText) rootView
                .findViewById(R.id.editText_register_userPassword);
        mEtUserPasswordAgain = (EditText) rootView
                .findViewById(R.id.editText_register_userPassword_again);

        mTxBack = (TextView) rootView.findViewById(R.id.rl_top_btn_back);

        mBtnReg.setOnClickListener(this);
        mTxBack.setOnClickListener(this);

        return rootView;
    }

    // 开始注册
    public void register() {
        final String password = mEtUserPassword.getText().toString();
        final String phone = mEtUserPhone.getText().toString();
        final String name = mEtUserNickName.getText().toString();


        //进行注册验证，注册个司机账号
        Date date = new Date();
        SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        String currentTime=time.format(date);
        WebUtil.postAddDriverUser1(WebUtil.getRpAddDriverUser1(phone,password,currentTime),new JsonHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                Gson gson = new Gson();
                try {
                    ServerRpsInfo serverRpsInfo = gson.fromJson(response.toString(), ServerRpsInfo.class);
                    if(serverRpsInfo.getStatus().equals("ok")&& serverRpsInfo.getMessage().equals("ok")) {
                        NlServerRps info = gson.fromJson(response.toString(), NlServerRps.class);
                        SingleToast.showToast(mAct, "注册成功，我是" + info.getData() + "个用户", 2000);
                        showRegisterSuccess();
                    }
                } catch (Exception e) {
                    SingleToast.showToast(mAct, "注册成功出错:"+e.getLocalizedMessage(), 2000);
                }
                progressDialogDismiss();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                SingleToast.showToast(mAct, "注册失败", 2000);
                progressDialogDismiss();
            }
        });

    }

    private void progressDialogDismiss() {
        if (progressDialog != null)
            progressDialog.dismiss();
    }

    private void progressDialogShow() {
        progressDialog = ProgressDialog
                .show(mAct,
                        mAct.getResources().getText(
                                R.string.dialog_message_title),
                        mAct.getResources().getText(
                                R.string.dialog_text_wait), true, false);
    }

    private void showRegisterSuccess() {
        new AlertDialog.Builder(mAct)
                .setTitle(
                        mAct.getResources().getString(
                                R.string.dialog_message_title))
                .setMessage(
                        mAct.getResources().getString(
                                R.string.success_register_success))
                .setNegativeButton(android.R.string.ok,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dialog.dismiss();
                                mFragmentCallBack.fragmentCallBack(
                                        LoginActivity.JUMP_2_LOGIN, null);
                            }
                        }).show();
    }

    // 进行注册前的格式验证
    private void doRegVerfy() {
        if (mEtUserPassword.getText().toString()
                .equals(mEtUserPasswordAgain.getText().toString())) {
            if (!mEtUserPassword.getText().toString().isEmpty()) {

                    if (!mEtUserPhone.getText().toString().isEmpty()) {
                        // 直接注册
                        progressDialogShow();
                        register();
                    } else {
                        showError(mAct
                                .getString(R.string.error_register_user_phone_null));
                    }
            } else {
                showError(mAct
                        .getString(R.string.error_register_password_null));
            }
        } else {
            showError(mAct
                    .getString(R.string.error_register_password_not_equals));
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_i_need_register:
                doRegVerfy();
                break;
            case R.id.rl_top_btn_back:
                mFragmentCallBack
                        .fragmentCallBack(LoginActivity.JUMP_2_LOGIN, null);
                break;
            default:
                break;
        }
    }

    public void doFragmentBackPressed() {
        mFragmentCallBack.fragmentCallBack(LoginActivity.JUMP_2_LOGIN, null);
    }

    ;
}
